package com.talis.controller;


import com.talis.constant.JwtClaimsConstant;
import com.talis.dto.EmploginDTO;
import com.talis.entity.Emp;
import com.talis.properties.JwtProperties;
import com.talis.result.Result;
import com.talis.service.impl.EmpService;
import com.talis.utils.JwtUtils;
import com.talis.vo.EmpLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理
 */
@RestController
@Slf4j
public class LoginController {

    @Autowired
    private EmpService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     *
     * @param emploginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<EmpLoginVO> login(@RequestBody EmploginDTO emploginDTO) {
        log.info("员工登录：{}", emploginDTO);

        Emp emp = employeeService.login(emploginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, emp.getId());
        String token = JwtUtils.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmpLoginVO empLoginVO = EmpLoginVO.builder()
                .id(emp.getId())
                .username(emp.getUsername())
                .name(emp.getName())
                .token(token)
                .build();

        return Result.success(empLoginVO);
    }


}
